package wangjg.xuexiban.activity.card;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import wangjg.commons.character.Random;
import wangjg.xuexiban.R;
import wangjg.xuexiban.entity.SimpleCard;
import wangjg.xuexiban.util.Constant;
import wangjg.xuexiban.util.FileDownCallback;
import wangjg.xuexiban.widget.MyViewPager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

public class ExamActivity2 extends CardPagerActivity {
	private static final int MSG_PAGETURN = 100;
	private Map<Integer, Boolean> result = new HashMap<Integer, Boolean>();

	protected void initContentView(){
		if(myPager==null){
	        myPager = (MyViewPager) findViewById(R.id.vPager);
	        myPager.setAdapter(new ListPagerAdapter(this.getCardList()) {
	    		protected View getItemView(int position) {
	    			if(position==list.size()){
	    				return getResultItemView();
	    			}
	    			return createPageView(position);
	    		}
	    		public int getCount() {
	    			return list.size()+1;
	    		}
	    	});
			myPager.setOnPageChangeListener(this);
		}
	}
	
	protected void loadDataList() {
		String categoryId = getIntent().getStringExtra("category_path");
		String url = Constant.URL_CARD_DOWN + (categoryId!=null?categoryId:"0");
		this.download(url, FileDownCallback.TYPE_DATA, null);
	}
	
	protected View createPageView(int position){
		this.myPager.setDiableTouch(true);
		final View itemView = this.inflate(R.layout.exam_item);
		final SimpleCard card = this.getCardList().get(position);
		String name = card.getName();
		String speechUrl = card.getSpeech();
		TextView tv = (TextView) itemView.findViewById(R.id.name);
		tv.setText(name);
		
		GridView gridView = (GridView) itemView.findViewById(R.id.exam_grid);
		this.createGridView(gridView, position, this.getCardList().size());
		
		this.download(Constant.fileUrl(speechUrl), FileDownCallback.TYPE_AUDIO, itemView.findViewById(R.id.imageView_play));
		return itemView;
	}
	
	private int[] getAnswers(int answer, int total){
		int[] answers = new int[4];
		int rightArrayIndex = Random.getRandomInt(0, 3);
		answers[rightArrayIndex] = answer;

		ArrayList<Integer> optList = new ArrayList<Integer>(total);
		for(int i=0;i<total;i++){
			if(i!=answer){
				optList.add(i);	
			}
		}
		
		if(optList.size()>0){
			for(int i=0;i<answers.length;i++){
				if(i==rightArrayIndex){
					continue;
				}
				int wrongIndex = Random.getRandomInt(0, optList.size()-1);
				int wrong = optList.get(wrongIndex);
				if(optList.size()>1){
					optList.remove(wrongIndex);
				}
				answers[i] = wrong;
			}
		}
		
		return answers;
	}
	
	protected void createGridView(GridView gridView, int position, int size) {
		Log.d(this.getClass().getSimpleName(), "initGridView");
		if(size==0){
			return;
		}
		ListAdapter gridAdapter = gridView.getAdapter();
		if(gridAdapter==null){
			int[] answer = this.getAnswers(position, size);
			gridAdapter = new GridAdapter(answer, position);
			gridView.setAdapter(gridAdapter);
		}
	}
	
	protected View getGridItemView(final int position, final int pagePosition) {
		final View gridItemView = this.inflate(R.layout.exam_option_item);
		SimpleCard card = this.getCardList().get(position);
		String picPath = card.getPicture();
		this.download(Constant.picUrl(picPath), FileDownCallback.TYPE_IMG, gridItemView.findViewById(R.id.image_option));
		
		gridItemView.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ImageView image_judge = (ImageView) gridItemView.findViewById(R.id.image_judge);
				image_judge.setVisibility(View.VISIBLE);
				Boolean right = position==pagePosition;
				if(right){
					image_judge.setImageResource(R.drawable.right);
					sendMessage(MSG_PAGETURN, position, 200);
				}else{
					image_judge.setImageResource(R.drawable.wrong);
				}
				if(result.get(pagePosition)==null){
					result.put(pagePosition, right);
				}
			}
	    });
		
		return gridItemView;
	}
	
	private void popupScore(){
		int f = this.getScore();
		
		new AlertDialog.Builder(
				ExamActivity2.this)
                .setTitle("成绩")
                .setMessage(f+"分")
                .setPositiveButton(
                    "确定",
                    new DialogInterface.OnClickListener() {  
                        public void onClick(DialogInterface dialog,int which) {  
                        	dialog.cancel();
                        }  
                    })
                .show();
	}
	
	private int getScore(){
		int rightCount = 0;
		if(result.size()==0){
			return 0;
		}
		for(boolean b:result.values()){
			if(b){
				rightCount++;
			}
		}
		int f = rightCount*100/result.size();
		return f;
	}
	
	@Override
	public void onPageScrollStateChanged(int position) {
		getResultItemView();
	}
	
	View resultView = null;
	
	protected View getResultItemView() {
		if(resultView==null){
			resultView = this.inflate(R.layout.exam_result);
		}
		TextView tv = (TextView) resultView.findViewById(R.id.score);
		tv.setText(getScore()+"");
		return resultView;
	}

	protected void handleMessage(Message msg) {
		if(msg.what==MSG_PAGETURN){
			Integer position = (Integer) msg.obj;
			myPager.setCurrentItem(position+1);
		}else{
			super.handleMessage(msg);
		}
	}

    public class GridAdapter extends BaseAdapter {
    	int pagePosition;
    	int[] answer;
    	
        public GridAdapter(int[] answer, int pagePosition) {
        	this.pagePosition = pagePosition;
        	this.answer = answer;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
        	int index = answer[position];
            return getGridItemView(index, pagePosition);
        }

        public final int getCount() {
        	return answer.length;
        }

        public final Object getItem(int position) {
            return position;
        }

        public final long getItemId(int position) {
            return position;
        }
    }
	
}

